package com.yang.library.client.menu;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yang.library.bookenum.State;
import com.yang.library.entry.User;
import com.yang.library.bookenum.TCPEnum;
import com.yang.library.util.AppContext;
import com.yang.library.util.Constant;
import com.yang.library.util.PrintUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class AdminUserManagementMenu implements Menu {
    private final ObjectMapper mapper = AppContext.getInstance().getMapper();
    private final Socket socket;

    public AdminUserManagementMenu(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void start() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
            while (true) {
                System.out.println("=========欢迎来到用户管理界面==========");
                System.out.println("1. 删除用户");
                System.out.println("2. 更新用户信息");
                System.out.println("3. 显示所有用户");
                System.out.println("4. 根据用户名查询用户");
                System.out.println("5. 退出用户管理界面");
                int type = PrintUtils.getIntInput(AppContext.getInstance().getScanner(), "请输入您的选择:");
                switch (type) {
                    case 1:
                        deleteUser(reader, writer);
                        break;
                    case 2:
                        updateUser(reader, writer);
                        break;
                    case 3:
                        getAllUser(reader, writer);
                        break;
                    case 4:
                        getUserByName(reader, writer);
                        break;
                    case 5:
                        return;
                    default:
                        System.out.println("输入错误，请重新输入！");
                        break;
                }
            }
        } catch (Exception e) {
            System.out.println("图书管理系统用户管理（管理员界面）异常");
            throw new RuntimeException(e);
        }
    }

    private void getUserByName(BufferedReader reader, BufferedWriter writer) throws Exception {
        String username = PrintUtils.getInput("请输入用户名：");
        // 向服务端发送请求
        writer.write(mapper.writeValueAsString(TCPEnum.USER_GET_USER_BY_NAME) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(username) + Constant.NEW_LINE);
        writer.flush();

        // 从服务端读取数据
        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        User user = mapper.readValue(responseMsg, User.class);
        if (user == null || user.getName() == null) {
            System.out.println("用户不存在！");
            return;
        }
        PrintUtils.printUsers(List.of(user));
    }

    private void getAllUser(BufferedReader reader, BufferedWriter writer) throws Exception {
        // 向服务器发送请求
        writer.write(mapper.writeValueAsString(TCPEnum.USER_GET_ALL_USERS) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务端的响应
        String responseMsg = reader.readLine();
        if (responseMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        List<User> users = mapper.readValue(responseMsg, new TypeReference<>() {
        });
        if (users == null || users.isEmpty()) {
            System.out.println("没有用户！");
            return;
        }
        PrintUtils.printUsers(users);
    }

    private void updateUser(BufferedReader reader, BufferedWriter writer) throws Exception {
        String username = PrintUtils.getInput("请输入要更新的用户名:");
        String password = PrintUtils.getInput("请输入要更新的密码:");
        String role = PrintUtils.getInput("请输入要更新的用户角色:");
        User user = new User(username, password, role);

        // 向服务器发送用户更新请求
        writer.write(mapper.writeValueAsString(TCPEnum.USER_UPDATE_USER) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(user) + Constant.NEW_LINE);
        writer.flush();

        // 获取服务器返回结果
        String resultMsg = reader.readLine();
        if (resultMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        State response = mapper.readValue(resultMsg, State.class);
        switch (response) {
            case SUCCESS:
                System.out.println("用户更新成功！");
                break;
            case FAILURE:
                System.out.println("用户更新失败！");
                break;
        }
    }

    private void deleteUser(BufferedReader reader, BufferedWriter writer) throws Exception {
        String username = PrintUtils.getInput("请输入要删除的用户名:");
        // 向服务端发送请求
        writer.write(mapper.writeValueAsString(TCPEnum.USER_DELETE_USER) + Constant.NEW_LINE);
        writer.write(mapper.writeValueAsString(username) + Constant.NEW_LINE);
        writer.flush();

        // 接收服务端返回
        String resultMsg = reader.readLine();
        if (resultMsg == null) {
            System.out.println("请检查网络连接！");
            return;
        }
        State response = mapper.readValue(resultMsg, State.class);
        switch (response) {
            case SUCCESS:
                System.out.println("删除成功！");
                break;
            case FAILURE:
                System.out.println("删除失败！");
                break;
        }
    }
}
